
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.sql.SQLException;
import java.sql.Blob;
import javax.imageio.ImageIO;
 
import java.io.IOException;
import java.sql.PreparedStatement;
import javax.sql.rowset.serial.SerialException;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;


/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author Mike
 */
public class ProfilePictureUploader extends javax.swing.JPanel {

    String username;
    Controller controller;
    DatabaseConnection dbConnect;
    JFrame caller;
    
    /**
     * Creates new form ProfilePictureUploader
     */
    public ProfilePictureUploader(Controller controller, DatabaseConnection dbConnect, JFrame caller) {
        this.controller = controller;
        this.dbConnect = dbConnect;
        this.caller = caller;
        initComponents();
        
        // Limit shown types to 'valid' images.
        jFileChooser1.setFileFilter(new ImageFileFilter());
    }
    
    public void setUsername(String s){
        username = s;
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jFileChooser1 = new javax.swing.JFileChooser();

        jFileChooser1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jFileChooser1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jFileChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(0, 0, Short.MAX_VALUE)
                .addComponent(jFileChooser1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jFileChooser1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jFileChooser1ActionPerformed
        javax.swing.JFileChooser theFileChooser = (javax.swing.JFileChooser)evt.getSource();
        String command = evt.getActionCommand();

        //click open
        if (command.equals(javax.swing.JFileChooser.APPROVE_SELECTION)) {
            try{
                //Get file
                File selectedFile = theFileChooser.getSelectedFile();
                
                System.out.println(selectedFile.getPath());
                
                //Change format to byte array to be stored in DB
                
                try {
                    BufferedImage image = ImageIO.read(selectedFile);
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    ImageIO.write(image, "png", baos);

                    //Write new image to DB
                    String picUpdateQuery = "UPDATE user SET pic = ?"+
                        " WHERE username = '" + username + "';";

                    dbConnect.connect();
                    Blob blob1 = dbConnect.conn.createBlob();
                    blob1.setBytes(1, baos.toByteArray());
                    
                    PreparedStatement preparedStatement =
                            dbConnect.conn.prepareStatement(picUpdateQuery);
                    preparedStatement.setBlob(1, blob1);
                    preparedStatement.execute();
                    dbConnect.closeConnection();
                    
                    controller.userProfile.setProfilePicture(image);

                } catch (SerialException ex) {
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
                controller.closeProfilePictureUploader();
            }
            catch(IOException e){
                e.printStackTrace();
            }
        } 
            //Handle cancel clicked
        else if (command.equals(javax.swing.JFileChooser.CANCEL_SELECTION)) {
            controller.closeProfilePictureUploader();
        }
    }//GEN-LAST:event_jFileChooser1ActionPerformed

    private class ImageFileFilter extends FileFilter
    {
        // Types supported by Java ImageIO natively.
        private final String[] imageExt = new String[]{
            ".jpg", ".png", ".bmp", ".gif"
        };
        
        @Override
        public boolean accept(File f) {
            if (f.isDirectory()) {
                return true;
            }
            
            for (String ext : imageExt) {
                if (f.getName().toLowerCase().endsWith(ext)) {
                    return true;
                }
            }
            
            return false;
        }
        
        @Override
        public String getDescription() {
            return "Image files";
        }
    }    
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser jFileChooser1;
    // End of variables declaration//GEN-END:variables
}
